package org.sosie2.service.audit;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.axis.message.SOAPEnvelope;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * 
 * This is the object that encapsulates the mail alert, including the parameters used for sending an email,
 * and the xpath condition that must be satisfied for the email to be sent.
 * 
 * @author Gabriela
 */
public class MailAlert {
	String xpath = null;
	String from = null;
	String to = null;
	String subject = null;
	String body = null;
	
	XPath xp = null;
	
	public MailAlert(String xpath, String from, String to, String subject, String body) {
		this.xpath = xpath;
		this.from = from;
		this.to = to;
		this.subject = subject.replaceAll("%x", xpath);
		this.body = body.replaceAll("%x", xpath);				
		
		xp = XPathFactory.newInstance().newXPath();		
	}
	
	/**
	 * This function returns true if the allert should be fired.
	 * 
	 * @param msg - the SOAPEnvelope to be examined
	 * @return boolean if the alert is or not to be fired
	 * @throws Exception
	 */
	public boolean fireAlert(SOAPEnvelope msg) throws Exception {
		Document document = msg.getAsDocument();
		Node temp = document.getFirstChild();
		Node soapMessage = temp.getLastChild();
		Boolean eval = (Boolean) xp.evaluate(xpath, soapMessage, XPathConstants.BOOLEAN);		
		return eval.booleanValue(); 
	}
	
	public String getXpath() {
		return this.xpath;
	}
	
	public String getFrom() {
		return from;				
	}
	
	public String getTo() {
		return to;
	}
	
	public String getSubject() {
		return subject;
	}
	
	public String getBody() {
		return body;
	}
	
	public String toString() {
		return "{" + xpath + "," + subject + "}"; 
	}
}

